package com.study.sbsummary.utils;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public class ExcelUtil {

    public static void getWorkbook(List<String> header, List<List<String>> dataList,HttpServletResponse response, String fileName) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("sheel");
        sheet.setDefaultColumnWidth(30);

        int rowCount = 0;
        Row row = sheet.createRow(rowCount);
        for (int i = 0; i < header.size(); i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(header.get(i));
        }
        if (CollectionUtils.isNotEmpty(dataList)) {
            for (List<String> data : dataList) {
                Row rows = sheet.createRow(++rowCount);
                for (int i = 0; i < data.size(); i++) {
                    Cell cells = rows.createCell(i);
                    cells.setCellValue(data.get(i));
                }
            }
        }
        OutputStream out = getResponseOutputStream(response, fileName);
        workbook.write(out);
        out.flush();
        out.close();
    }

    public static OutputStream getResponseOutputStream(HttpServletResponse response, String fileName) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        OutputStream out = response.getOutputStream();
        return out;
    }
}
